package com.gismore.parser.excel.common.util;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lei on 2017/6/23.
 */
public class PropertiesUtils {

	public static Properties loadConfigProperties(String configFileName){
		String configFilePath = classPath(configFileName);
		Properties properties = new Properties();
		try {
			String configFileContent = Files.toString(new File(configFilePath), Charsets.UTF_8);
			properties.load(new StringReader(configFileContent));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return properties;
	}

	public static String loadConfigContent(String configFileName){
		String configFilePath = classPath(configFileName);
		String configFileContent = null;
		try {
			configFileContent = Files.toString(new File(configFilePath), Charsets.UTF_8);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return configFileContent;
	}

	public static String classPath(String relativePath){
		if(relativePath == null){
			relativePath = "";
		}
		String classPath = Resources.getResource(PropertiesUtils.class,"").getFile();
		String configFileBasePath;
		Pattern jarPattern = Pattern.compile("^(file:)*(?<classPath>\\S+)/\\S+\\.jar\\S+$");
		Matcher jarMatcher = jarPattern.matcher(classPath);
		if(jarMatcher.find()){
			configFileBasePath = jarMatcher.group("classPath")+"/conf/";
		}else{
			configFileBasePath = StringUtils.substringBefore(classPath,"classes/")+"classes/";
		}
		return configFileBasePath+relativePath;
	}
}
